<script setup>
import { useNavbarStore } from '../../stores/navbar'
import { onMounted, ref, nextTick } from 'vue'
import { Search } from '@element-plus/icons-vue'
import connectCardContainer from '@/components/connectCardContainer.vue'
import { useUserStore } from '@/stores/user.js'
import http_message from '@/api/message.js'
import http_login from '@/api/login.js'
import http_posts from '@/api/posts.js'
import EmojiPicker from 'vue3-emoji-picker'
import 'vue3-emoji-picker/css'
import { ElMessage } from 'element-plus'
import { useRoute } from 'vue-router'
import { useAesStore } from '@/stores/aes.js'

const navbarStore = useNavbarStore()
const useStore = useUserStore()
const route = useRoute()
const aesStore = useAesStore()

const messageData = ref({}) //聊天的数据
const userList = ref([]) //用户数据列表
// 获得聊天数据
const getMessage = async () => {
  const result = await http_message.getMessage(useStore.userInfo.userId)
  if (result.code === 200) {
    // 排序,按照最后一条短信时间先后
    result.data.connect = result.data.connect.sort(
      (a, b) =>
        new Date(b.message[b.message.length - 1].time) -
        new Date(a.message[a.message.length - 1].time)
    )
    messageData.value = result.data
    const data = messageData.value.connect
    for (let i = 0; i < data.length; i++) {
      getUserInfo(data[i].userId)
    }
  }
}
// 获得用户信息
const getUserInfo = async (userId) => {
  const result = await http_login.getUserInfobyId(userId)
  if (result.code === 200) {
    userList.value.push(result.data)
  }
}
// 用户头像回到顶层
const userCardToTop = (userId) => {
  //userId:和那个用户聊天的id
  let index = 0
  for (let i = 0; i < userList.value.length; i++) {
    if (userList.value[i].userId === userId) {
      index = i
      break
    }
  }
  if (index !== 0) {
    const data1 = userList.value[index]
    userList.value.splice(index, 1)
    userList.value.unshift(data1)

    const data2 = messageData.value.connect[index]
    messageData.value.connect.splice(index, 1)
    messageData.value.connect.unshift(data2)
    // 整理MessageData数据
    // for (let i = 0; i < userList.value.length; i++) {
    //   for (let j = 0; i < messageData.value.connect.length; j++) {
    //     if (userList.value[i].userId === messageData.value.connect[j].userId) {
    //       const data = messageData.value.connect[j]
    //       messageData.value.connect[j] = messageData.value.connect[i]
    //       messageData.value.connect[i] = data
    //     }
    //   }
    // }
  }
}
// 获得用户信息
const getPostsInfo = async (postsId) => {
  const result = await http_posts.getPostsInfo(postsId)
  if (result.code === 200) {
    currentPostsInfo.value = result.data
  }
}
const currentPostsInfo = ref({})
const currentMessageData = ref({}) //目前聊天记录
const currentUserInfo = ref({}) //选中聊天会话的用户id
const show = ref(true) //是否显示空状态
// 选择聊天会话
const selectConnect = (item) => {
  show.value = false
  currentUserInfo.value = item
  for (let i = 0; i < messageData.value.connect.length; i++) {
    if (item.userId === messageData.value.connect[i].userId) {
      currentMessageData.value = messageData.value.connect[i]
      if (messageData.value.connect[i].postsId === '1') {
        currentPostsInfo.value = {
          name: 'BOSS直聘官方客服',
          salary: '上班时间:工作日 9:00-17:00',
          city: 'BOSS直聘有限公司'
        }
      } else {
        getPostsInfo(messageData.value.connect[i].postsId)
      }
      break
    }
  }
  currentMessageData.value.number = 0
  http_message.clearNumber(
    useStore.userInfo.userId,
    currentUserInfo.value.userId
  )
  //
  increaseWidth()
}
const inputValue = ref('') //聊天框输入的内容
// 按下回车发送消息
const handleEnter = async () => {
  const value = inputValue.value
  inputValue.value = '' //尽快的清空
  // 先不往后端发送请求，而且直接添加在MessageData中，之后再向后端发送请求
  const data = {
    content: value,
    status: 0,
    type: 0,
    time: new Date()
      .toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      })
      .replace(/\//g, '-')
  }
  currentMessageData.value.message.push(data)
  increaseWidth()
  userCardToTop(currentMessageData.value.userId)
  // 向后端发送请求
  http_message.saveMessage(
    data,
    messageData.value.userId,
    currentMessageData.value.userId
  )
}
// 选中表情包函数
function onSelectEmoji(emoji) {
  inputValue.value += emoji.i
  /*
    // result
    { 
        i: "😚", 
        n: ["kissing face"], 
        r: "1f61a", // with skin tone
        t: "neutral", // skin tone
        u: "1f61a" // without tone
    }
    */
}
// 按下ctrl+enter换行
const handleCtrlEnter = () => {
  inputValue.value += '\n'
}
const commonList = ref([
  '对不起，我觉得职位不太适合我，祝您早日找到满意的工作人选。',
  '我可以去贵公司面试吗？',
  '我可以把简历发给你看看吗？'
]) //常用语言
// 发送图片函数
const beforeImgUpload = (rawFile) => {
  if (!(rawFile.type === 'image/jpeg' || rawFile.type === 'image/png')) {
    ElMessage.error('图片必须是jpg或者png格式')
    return false
  } else if (rawFile.size / 1024 / 1024 > 10) {
    ElMessage.error('图片必须小于10MB')
    return false
  }
  return true
}
// 发送图片成功
const imguploadSuccess = (response) => {
  const data = {
    content: response.data,
    status: 0,
    type: 2,
    time: new Date()
      .toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      })
      .replace(/\//g, '-')
  }
  currentMessageData.value.message.push(data)
  increaseWidth()
  userCardToTop(currentMessageData.value.userId)
  // 后端发送请求保存
  http_message.saveMessage(
    data,
    messageData.value.userId,
    currentMessageData.value.userId
  )
}
const srcList = ref([]) //图片预览
// 设置预览图片
const setSrcList = (data) => {
  srcList.value = []
  srcList.value.push(data)
}
// 发送消息之后让滚动条到底部
const myDiv = ref(null)
const increaseWidth = () => {
  nextTick(() => {
    // 使用nextTick确保DOM更新后执行滚动操作
    setTimeout(() => {
      //
      myDiv.value.scrollTo({
        top: myDiv.value.scrollHeight,
        behavior: 'smooth'
      }) //滚动到底部
    }, 0)
  })
}
const connectIsExist = async () => {
  await http_message.connectIsExist(
    useStore.userInfo.userId,
    route.query.connectId,
    route.query.postsId
  )
}
onMounted(() => {
  window.scrollTo(0, 0)
  if (
    route.query.connectId !== undefined &&
    route.query.postsId !== undefined
  ) {
    connectIsExist()
  }
  navbarStore.setFlag(false)
  setTimeout(() => {
    getMessage()
    if (
      route.query.connectId !== undefined &&
      route.query.postsId !== undefined
    ) {
      setTimeout(() => {
        for (let i = 0; i < userList.value.length; i++) {
          if (route.query.connectId === userList.value[i].userId) {
            selectConnect(userList.value[i])
            break
          }
        }
      }, 800)
    }
  }, 100)
})
// webSocket操作
const socket = new WebSocket(
  'ws://127.0.0.1:10011/api/v1/webSocket/' + useStore.userInfo.userId
) //TODO：456改为用户id
socket.onmessage = function (event) {
  // 接收到webSocket推送的消息 1.number+1 2. currentData 3.messageData
  const data = JSON.parse(aesStore.Decrypt(event.data))
  console.log(data)
  if (
    Object.keys(currentMessageData.value).length === 0 ||
    currentMessageData.value.userId !== data.userId
  ) {
    //表示未选择对话，或者不在当前对话的用户
    for (let i = 0; i < messageData.value.connect.length; i++) {
      if (data.userId === messageData.value.connect[i].userId) {
        messageData.value.connect[i].message.push(data.messageItem)
        messageData.value.connect[i].number =
          messageData.value.connect[i].number + 1
        break
      }
    }
  } else {
    currentMessageData.value.message.push(data.messageItem)
    for (let i = 0; i < messageData.value.connect.length; i++) {
      if (data.userId === messageData.value.connect[i].userId) {
        messageData.value.connect[i].message.push(data.messageItem)
        break
      }
    }
  }
}
</script>

<template>
  <div class="connect-box">
    <div class="content">
      <div class="left">
        <div>
          <el-input
            class="w-50 m-2"
            placeholder="搜索30天内的联系人"
            :suffix-icon="Search"
            style="width: 90%; margin-top: 15px; margin-left: 15px"
          />
        </div>
        <div style="margin-left: 15px; margin-top: 15px">
          <div class="button">全部</div>
          <div class="button">新招呼</div>
          <div class="button">仅沟通</div>
          <div class="button">有交换</div>
          <div class="button">有面试</div>
        </div>
        <div style="height: 550px; overflow-y: scroll">
          <div
            @click="selectConnect(item)"
            v-for="(item, index) in userList"
            :key="item.userId"
          >
            <connectCardContainer
              :class="[currentUserInfo.userId === item.userId ? 'active' : '']"
              :userData="item"
              :messageData="
                messageData.connect[index].message[
                  messageData.connect[index].message.length - 1
                ]
              "
              :number="messageData.connect[index].number"
            />
          </div>
          <div
            style="
              font-size: 12px;
              color: #999;
              text-align: center;
              margin-top: 20px;
            "
          >
            没有更多了
          </div>
        </div>
      </div>
      <div class="right">
        <div v-if="show" style="margin-top: 100px">
          <el-empty description="与您进行过沟通的BOSS都会在左侧列表中显示" />
        </div>
        <div v-else>
          <div
            style="
              font-size: 16px;
              color: #666;
              margin-left: 30px;
              margin-top: 10px;
            "
          >
            <span style="margin-right: 20px">{{
              currentUserInfo.username
            }}</span>
            <span>{{ currentUserInfo.companyName }}</span>
            <span> | </span>
            <span>{{ currentUserInfo.duties }}</span>
          </div>
          <div class="title">
            <span style="margin-left: 20px">{{ currentPostsInfo.name }}</span>
            <span style="margin-left: 30px; color: red">{{
              currentPostsInfo.salary
            }}</span>
            <span style="margin-left: 30px">{{ currentPostsInfo.city }}</span>
          </div>
          <div ref="myDiv" class="contentBox">
            <!-- TODO -->
            <div
              v-for="(item, index) in currentMessageData.message"
              :key="index"
              style="position: relative"
              :class="item.status === 0 ? 'position' : ''"
            >
              <div :class="['text', item.status === 0 ? 'position' : '']">
                <span v-if="item.type === 0">{{ item.content }}</span>
                <span v-else-if="item.type === 1">表情包</span>
                <span v-else-if="item.type === 2">
                  <el-image
                    style="max-width: 380px"
                    :src="item.content"
                    :zoom-rate="1.2"
                    :max-scale="7"
                    :min-scale="0.2"
                    :initial-index="4"
                    :preview-src-list="srcList"
                    fit="cover"
                    @click="setSrcList(item.content)"
                  />
                </span>
              </div>
            </div>
            <div style="height: 10px"></div>
          </div>
          <div class="send">
            <div class="icon">
              <el-popover placement="top" width="300px" trigger="click">
                <template #reference>
                  <span>
                    <el-tooltip
                      class="box-item"
                      effect="dark"
                      content="表情包"
                      placement="top"
                    >
                      <span class="iconfont icon-xiaolian"></span>
                    </el-tooltip>
                  </span>
                </template>
                <div>
                  <EmojiPicker :native="true" @select="onSelectEmoji" />
                </div>
              </el-popover>
              <el-popover placement="top" width="400px" trigger="click">
                <template #reference>
                  <span>
                    <el-tooltip
                      class="box-item"
                      effect="dark"
                      content="常用语"
                      placement="top"
                    >
                      <span
                        style="font-size: 27px"
                        class="iconfont icon-kaiqilingsheng"
                      ></span>
                    </el-tooltip>
                  </span>
                </template>
                <div>
                  <div
                    style="
                      width: 100%;
                      background: linear-gradient(to right, #f5fcfc, #fbfbfa);
                      height: 30px;
                      line-height: 30px;
                      font-size: 16px;
                      padding-left: 10px;
                      border-radius: 5px;
                      margin-left: -5px;
                    "
                  >
                    <span>常用语</span>
                    <span
                      style="
                        font-size: 12px;
                        color: #409eff;
                        position: relative;
                        left: 290px;
                        cursor: pointer;
                      "
                      >设置</span
                    >
                  </div>
                  <div style="width: 96%">
                    <ul style="font-size: 13px; margin-left: -35px">
                      <div
                        class="common"
                        v-for="(item, index) in commonList"
                        :key="index"
                        @click="inputValue += item"
                      >
                        <li class="common1">
                          <el-icon><InfoFilled /></el-icon>
                          {{ item }}
                        </li>
                      </div>
                    </ul>
                  </div>
                </div>
              </el-popover>
              <el-upload
                style="display: inline-block"
                action="/api/v1/client/message/uploadImgMessage"
                :before-upload="beforeImgUpload"
                :on-success="imguploadSuccess"
                :show-file-list="false"
              >
                <span>
                  <el-tooltip
                    class="box-item"
                    effect="dark"
                    content="图片"
                    placement="top"
                  >
                    <span class="iconfont icon-tupian"></span>
                  </el-tooltip>
                </span>
              </el-upload>
              <span style="margin-left: 30px" class="button">发简历</span>
              <span class="button">换微信</span>
              <span class="button">换电话</span>
              <span style="margin-left: 80px; position: relative; top: -5px"
                >按Enter键发送，按Ctrl+Enter键换行</span
              >
            </div>
            <div style="margin-left: 15px">
              <el-input
                v-model="inputValue"
                :rows="5"
                type="textarea"
                style="width: 98%"
                @keyup.enter="handleEnter"
                @keyup.ctrl.enter="handleCtrlEnter"
              />
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.connect-box {
  width: 100%;

  height: 89vh;
  background-color: #def4f5;
  padding-top: 10px;
  .content {
    width: 80%;
    margin: 0 auto;
    background-color: #def4f5;
    height: 98%;
    border-radius: 20px;
    display: flex;
    .left {
      flex: 2;
      height: 100%;
      background-color: #fff;
      border-radius: 20px;
      margin-right: 5px;
      .button {
        background-color: #eee;
        color: #333;
        padding: 5px;
        font-size: 12px;
        margin-left: 15px;
        display: inline-block;
      }
      .active {
        background-color: rgba($color: #ccc, $alpha: 0.3);
      }
    }
    .right {
      flex: 5;
      height: 100%;
      background-color: #fff;
      border-radius: 20px;
      .title {
        width: 98%;
        height: 50px;
        margin: 0 auto;
        border-radius: 10px;
        margin-top: 15px;
        font-size: 18px;
        line-height: 50px;
        background: linear-gradient(to right, #f5fcfc, #fcfbfa);
      }
      .contentBox {
        height: 390px;
        width: 100%;
        overflow-y: scroll;
        .text {
          padding: 10px;
          background-color: #ccf2f2;
          margin-top: 15px;
          max-width: 380px;
          word-wrap: break-word;
          border-radius: 5px;
          margin-left: 15px;
          display: inline-block;
          line-height: 23px;
        }
        .position {
          display: flex;
          justify-content: end;
          margin-right: 10px;
          // position: absolute;  //会产生高度塌陷问题
          // right: 20px;
          // text-align: right;
        }
      }
      .send {
        border-top: 1px solid #ccc;
        .icon {
          font-weight: 900;
          margin-left: 10px;
          margin-top: 5px;

          .button {
            display: inline-block;
            color: #ccc;
            font-weight: normal;
            border: 1px solid #ccc;
            padding: 2px 5px;
            border-radius: 6px;
            margin-left: 15px;
            cursor: pointer;
            position: relative;
            top: -4px;
          }
          .iconfont {
            font-size: 24px;
            margin-left: 30px;
            cursor: pointer;
          }
          .iconfont:hover {
            color: #7ccdcd;
          }
        }
      }
    }
  }
}
.common1 {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  cursor: pointer;
}
.common {
  padding: 7px;
  border-radius: 5px;
}
.common:hover {
  background-color: #eee;
}
</style>
